package com.jiuyou.clientController.mall.comment;

import com.alibaba.fastjson.JSONObject;
import com.jiuyou.clientController.base.ClientBaseController;
import com.ruoyi.adapayDiv.service.IAdapayDivService;
import com.ruoyi.adapayMember.domain.AdapayMember;
import com.ruoyi.adapayMember.service.IAdapayMemberService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.controller.HandleVideoSrc;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shopping.domain.*;
import com.ruoyi.shopping.service.*;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chengliang
 * @date 2022/6/20
 **/
@RestController
@RequestMapping("/client/mall/comment")
public class MallCommentClientController extends ClientBaseController {
    @Autowired
    private IMallCommentService commentService;
    @Autowired
    private IMallOrderService orderService;
    @Autowired
    private IMallProductService productService;
    @Autowired
    private IMallOrderMeshService meshService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IMallIntegralService integralService;
    @Autowired
    private IMallIntegralRecordService integralRecordService;
    @Autowired
    private IAdapayDivService divService;
    @Autowired
    private IAdapayMemberService adapayMemberService;
    @Autowired
    private IMallBindService bindService;
    @PostMapping("/getList/{productId}")
    public AjaxResult getList(@PathVariable Long productId){
        MallComment mallComment = new MallComment();
        mallComment.setProductId(productId);
        startPage();
        List<MallComment> list = commentService.selectMallCommentList(mallComment);
        TableDataInfo dataTable = getDataTable(list);
        HashMap<String, Object> map = new HashMap<>(2);
        List<JSONObject> objects = new ArrayList<>();
        list.forEach(e->{
            JSONObject jso = new JSONObject();
            jso.put("memberImg",e.getMemberHeadImg());
            jso.put("memberName",e.getMemberNickName());
            jso.put("level",e.getPlatformLevel());
            jso.put("commentText",e.getCommentContent());
            jso.put("commentImg",e.getCommentImages());
            jso.put("commentVideo",e.getCommentVideo());
            jso.put("videoCover",e.getVideoCover());
            jso.put("platformText",e.getPlatformContent());
            objects.add(jso);
        });
        map.put("totalNum",dataTable.getTotal());
        map.put("data",objects);
        return AjaxResult.success(map);
    }

    @PostMapping("/create")
    public AjaxResult create(@RequestBody MallComment comment){
        MallProduct mallProduct= productService.selectMallProductById(comment.getProductId());
        Member member = getLoginMember().getMember();
        comment.setMemberHeadImg(member.getHeadImg());
        comment.setMemberId(member.getId());
        comment.setProductName(mallProduct.getProductName());
        comment.setMemberNickName(member.getNickName());
        MallOrder mallOrder = orderService.selectMallOrderById(comment.getOrderId());
        comment.setProductName(mallOrder.getProductName());
        if(StringUtils.isNotEmpty(comment.getCommentVideo())){
            Map<String, String> val = configService.getVal();
            comment.setVideoCover(HandleVideoSrc.handle(val.get("key"),val.get("id"),val.get("region"),val.get("bn"),comment.getCommentVideo()));
        }
        commentService.insertMallComment(comment);
        mallOrder.setCommentStatus(DicConstants.SYS_Y.getCode());
        orderService.updateMallOrder(mallOrder);
        List<MallOrder> mallOrders = orderService.selectMallOrderByMeshId(mallOrder.getMergeOrderId());
        int count = 0;
        for (MallOrder order : mallOrders) {
            if(DicConstants.SYS_Y.getCode().equals(order.getCommentStatus())){
                count++;
            }
        }
        if(count == mallOrders.size()){
            MallOrderMesh mallOrderMesh = meshService.selectMallOrderMeshById(mallOrder.getMergeOrderId());
            mallOrderMesh.setCommentState(DicConstants.SYS_Y.getCode());
            mallOrderMesh.setOrderState(DicConstants.ORDER_STATE_FINISHED.getCode());
            meshService.updateMallOrderMesh(mallOrderMesh);
            //分销处理
            MallBind bind = bindService.selectMallBindByMemberId(mallOrderMesh.getMemberId());
            if(bind != null) {
                AdapayMember adapayMember = new AdapayMember();
                adapayMember.setStoreId(bind.getStoreId());
                List<AdapayMember> list = adapayMemberService.selectAdapayMemberList(adapayMember);
                if(list.size()>0){
                    adapayMember = list.get(0);
                    for (MallOrder order : mallOrders) {
                        if(DicConstants.SYS_N.getCode().equals(order.getAfterSalesState())){
                            BigDecimal distribution = new BigDecimal(configService.selectConfigByKey("distribution")).divide(new BigDecimal("100"));
//                            BigDecimal subtract = order.getPayPrice().subtract(distribution);
                            BigDecimal subtract = order.getPayPrice().multiply(distribution).setScale(2, RoundingMode.HALF_UP);
                            divService.mallOrderDiv(bind.getStoreId(),adapayMember,mallOrderMesh,subtract);
                        }
                    }
                }
            };

            handleIntegral(mallOrderMesh,mallOrders);
        }
        orderService.checkFinished(mallOrder.getMergeOrderId());

        return AjaxResult.success();
    }
    //获取积分处理
    private void handleIntegral(MallOrderMesh mesh,List<MallOrder> orders) {
        String consume=configService.selectConfigByKey("consume");
        if(StringUtils.isEmpty(consume)){
            return;
        }
        BigDecimal integral = Arith.getBigDecimal(consume);
        if(null==integral||integral.compareTo(BigDecimal.ZERO)==0){
            return;
        }
        MallOrder mallOrder = new MallOrder();
        mallOrder.setMemberId(mesh.getMemberId());
        mallOrder.setMergeOrderId(mesh.getId());
        BigDecimal total = BigDecimal.ZERO;
        for (MallOrder order : orders) {
            //缺少判断订单是否需要计算
            if(DicConstants.SYS_N.getCode().equals(order.getAfterSalesState())) {
                total = total.add(order.getPayPrice());
            }
        }
        if(total.compareTo( BigDecimal.ZERO)==0){
            return;
        }
        BigDecimal divide = total.divide(integral,0, BigDecimal.ROUND_DOWN);
        mesh.setGainIntegral(divide.longValue());
        mesh.setPayPrice(total);
        mesh.setPayState(DicConstants.SYS_N.getCode());
        MallIntegral mallIntegral = new MallIntegral();
        mallIntegral.setUserId(mesh.getMemberId());
        List<MallIntegral> mallIntegrals = integralService.selectMallIntegralList(mallIntegral);
        if(mallIntegrals.size()>0){
            MallIntegral in = mallIntegrals.get(0);
            in.setIntegralBalance(in.getIntegralBalance().add(divide));
            mallIntegral.setIntegralBalance(in.getIntegralBalance());
            integralService.updateMallIntegral(in);
        }else{
            mallIntegral.setIntegralBalance(divide);
            integralService.insertMallIntegral(mallIntegral);
        }
        MallIntegralRecord record = new MallIntegralRecord();
        record.setUserId(mesh.getMemberId());
        record.setDepict("商城消费"+mesh.getPayPrice().toString()+"元");
        record.setHandleType(DicConstants.INTEGRAL_TYPE_POINT.getCode());
        record.setHandleDirection("in");
        record.setHandleIntegral(divide);
        record.setIntegralBalance(mesh.getPayPrice());
        integralRecordService.insertMallIntegralRecord(record);
        orders.clear();
    }
}
